<?php
// +----------------------------------------------------------------------
// | EtrolPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Author: Author: HCZ <huangchengze@etrol.com>
// +----------------------------------------------------------------------

namespace app\warning\controller\api;
use app\common\controller\Api;
use app\warning\library\Evaluation as autoEvaluation;

/**
 * 风险评估
 * @package app\warning\api
 * @author LJQ<liujiqi@etrol.com>
 */
class Evaluation extends Api{

    /**
     * 获取评分
     * @param string $enterpriseId
     * @return json
     */
    public function getEvaluationList($enterpriseId=null){
    	// 风险评估
        $grade = model('evaluation')->where(array('enterpriseId'=>$enterpriseId))->find()->toArray();
        if(empty($grade)){
            $model = model('evaluation');
            $model->data(['enterpriseId'=>$enterpriseId]);
            $model->allowField(true)->save();
            $grade = $model->where(array('enterpriseId'=>$enterpriseId))->find()->toArray();
        }
        $info = collection(model('admin/Config')->where(array('groupName'=>'warning'))->select())->toArray();
        $scoring = config('scoring');
        foreach($info as &$item){
        	$item['grade'] = $grade[strtolower($item['name'])];
        	$item['scoring'] = $scoring[$item['name']];
        	$item['name'] = strtolower($item['name']);
        	if(in_array(strtolower($item['name']),model('evaluation')->autoElement)){
        		$item['disabled'] = 'disabled';
        	}else{
        		$item['disabled'] = '';
        	}
        }
        $send_url = url('warning/evaluation/edit',array('enterpriseId'=>$enterpriseId));
        return json(['code'=>1,'msg'=>'','count'=>count($info),'data'=>['info'=>$info,'url'=>$send_url]]);
    }

    public  function  c2($enterpriseId){

        $res=db('chemicaldata')->alias('a')
            ->join('access_chemical b','a.id=b.chemicalId and a.enterpriseId='.$enterpriseId)
            ->field('sum(stock) as sum,a.limit')->group('a.id')->select();

        if($res){
            $arr=[];
            foreach ($res as $key=>$value){
                $arr[$key]=$value["sum"]/$value['limit'];
            }
            $Q= array_sum($arr);
            switch($Q){
                case $Q>=1:
                    $result=model('warning/evaluation')->where(array('enterpriseId'=>$enterpriseId))->update(['c2'=>100]);
                    break;

                case 0.1<=$Q&&$Q<1:
                    $result=model('warning/evaluation')->where(array('enterpriseId'=>$enterpriseId))->update(['c2'=>50]);
                    break;

                case 0<=$Q&&$Q<0.1:
                    $result=model('warning/evaluation')->where(array('enterpriseId'=>$enterpriseId))->update(['c2'=>0]);
                    break;

            }
        }else{
            $result=model('warning/evaluation')->where(array('enterpriseId'=>$enterpriseId))->update(['c2'=>0]);

        }
    }
    
    public function autoScoring($enterpriseId = null){
    	if($enterpriseId == null){
    		return json(['code'=>0,'msg'=>'未选择企业,请检查']);
    	}
    	$evaluation = new autoEvaluation();
    	$result['c1'] = $evaluation->c1($enterpriseId);
    	$result['c2'] = $evaluation->c2($enterpriseId);
    	$result['c3'] = $evaluation->c3($enterpriseId);
    	$result['c15'] = $evaluation->c15($enterpriseId);
    	$result['c18'] = $evaluation->c18($enterpriseId);
    	return json(['code'=>1,'msg'=>'评分成功','data'=>$result]);
    }

    /**
     * 上传评分
     * @param string $data
     * @param string $enterpriseId
     * @return json
     */
    public  function edit($data = null,$enterpriseId = null){
        if($enterpriseId == null){
            return json(['code'=>0,'msg'=>'未选择企业,请检查']);
        }
        if($data == null){
            $data = input('post.');
        }
        $model = model('evaluation');
        
        $id = $model->where(array('enterpriseId'=>$enterpriseId))->value('id');
        if($model->save($data,['id'=>$id]) !== false && $this->archive($data,$enterpriseId) !== false){
            return json(['code'=>1,'msg'=>'归档成功']);
        }
        return json(['code'=>0,'msg'=>'修改失败']);

    }
    
    

    /**
     * 评分归档
     * @param string $data
     * @param string $enterpriseId
     * @return json
     */
    private function archive($data = null,$enterpriseId = null){
    	if(!$data || !$enterpriseId){
    		return false;
    	}else {
    		$model = model('Warning');
    		$score_group = $model->scoreGroup;
    		$scoring_weight = config('warning');
    		$risk_degree = config('risk_degree');
    		$techniqueValue = 0;
    		foreach($score_group['technique'] as $item){
				$techniqueValue += $data[$item]*$scoring_weight[strtoupper($item)];
			}
			$equipmentValue = 0;
			foreach($score_group['equipment'] as $item){
				$equipmentValue += $data[$item]*$scoring_weight[strtoupper($item)];
			}
			$workingValue = 0;
			foreach($score_group['working'] as $item){
				$workingValue += $data[$item]*$scoring_weight[strtoupper($item)];
			}
			$behaviorValue = 0;
			foreach($score_group['behavior'] as $item){
				$behaviorValue += $data[$item]*$scoring_weight[strtoupper($item)];
			}
			$manageValue = 0;
			foreach($score_group['manage'] as $item){
				$manageValue += $data[$item]*$scoring_weight[strtoupper($item)];
			}
			//总分
			$generalValue = $techniqueValue+$equipmentValue+$workingValue+$behaviorValue+$manageValue;
			//预警等级
			foreach($risk_degree as $key => $degree){
				if($generalValue >= $degree[0] && $generalValue < $degree[1]){
					$riskDegree = $key;
					break;
				}
			}
			
			$early_warning = [
					'techniqueValue' => $techniqueValue,
					'equipmentValue' => $equipmentValue,
					'workingValue'   => $workingValue,
					'behaviorValue'  => $behaviorValue,
					'manageValue'    => $manageValue,
					'generalValue'   => $generalValue,
					'riskDegree'     => $riskDegree,
					'enterpriseId'   => $enterpriseId,
			];
			//更新预警评分并记录
			if($model->save($early_warning,['enterpriseId'=>$enterpriseId]) && model('Warninghistory')->save($early_warning)){
				return true;
			}
			return false;
    	}
    }
}